package com.example.security;

import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.example.dao.UserDao;
import com.example.entity.bean.UserBean;
import com.example.entity.entity.UserEntity;

@Service
public class JwtUserDetailsService implements UserDetailsService {

	@Autowired
	private UserDao userRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserEntity userEntity = userRepository.findByUsername(username);
		if (userEntity == null) {
			throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
		} else {
			UserBean userBean = new UserBean(userRepository.findByUsername(username));
			return new JwtUser(userBean.getUsername(), userBean.getPassword(),
					userBean.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
		}
	}

}
